package com.youan.log.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import org.apache.commons.io.FileUtils;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.FileUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

public class ExcelUtils {
    public static <T,V> String wirte2Excel(Class<T> templateBean, List<V> dataList) {
        String filePath = FileUtil.getTempDirPath() + File.separator + System.currentTimeMillis() + ".xlsx";
        // 这里 需要指定写用哪个class去写
        ExcelWriter excelWriter = null;
        try {
            excelWriter = EasyExcel.write(filePath, templateBean).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("信息").build();
            excelWriter.write(dataList, writeSheet);
        } finally {
            // 千万别忘记finish 会帮忙关闭流
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
        return filePath;
    }

    public static void exportExcel(String filePath, HttpServletResponse response, Boolean isDeleteOriginFile) {
        File file = new File(filePath);
        // 取得文件名。
        if (file.exists()) {
            response.setContentType("application/octet-stream");
            response.setHeader("content-type", "application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;fileName=download" + DateUtil.time() + ".xlsx" );// 设置文件名
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        if(isDeleteOriginFile) {
            FileUtils.deleteQuietly(file);
        }
    }
}
